#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License,  Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http: //www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,  software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,  either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#shit
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
import urllib2
import urllib
import simplejson as json
import os
from google.appengine.ext.webapp import template
import datetime
from google.appengine.ext import db
import sys
from DataClasses import FbUser
import base64
import hashlib
import hmac

ACCESS_URL = "https://graph.facebook.com/oauth/access_token?"
GRAPH_URL = "https://graph.facebook.com/me?"


class DataAccessLayer():

###Datastore methods
    def remove_all_data_from_datastore(self):
        db.delete(db.Query())

    def query_multiple_data_from_datastore(self):
        character_query = Character.all()
        ##character_query.filter("name  = ",  "Chuzzlefritz")
        results = character_query.fetch(5)
        for result in results:
            self.response.out.write(result.name)

    def post_test_data_to_datastore(self):
        character = Character(name="Chuzzlefritz", level=85)
        character.put()

    def query_one_entity_test_data_from_datastore(self):
        character_k = db.Key.from_path('Character', 6)
        character_data = db.get(character_k)
        self.response.out.write(character_data.name + character_data.level)

    def fetch_race_from_data(self, race_data, requested_race):
        for race in race_data['races']:
            if race['id'] == requested_race:
                return race

    def fetch_class_from_data(self, class_data, requested_class):
        for wow_class in class_data['classes']:
            if wow_class['id'] == requested_class:
                return wow_class

###facebook record saving
    def save_fb_user_record(self, fb_user_id, fb_user_name):
        fb_user_data = FbUser(id=int(FbUserId), fullname=unicode(fb_user_name))
        output = fb_user_data.put()
        if output:
            return output

    def fetch_fb_user_record_by_fb_user_id(self, fb_user_id):
        fb_user_query = FbUser.all()
        fb_user_query.filter("id =", int(fb_user_id))
        results = FbUser_query.fetch(1)
        return results

###facebook signed request decoding
    def base64_url_decode(self, inp):
        padding_factor = (4 - len(inp) % 4) % 4
        inp += "=" * padding_factor
        decoded = unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/')))
        return base64.b64decode(decoded)

    def parse_signed_request(self, signed_request, secret):
        l = signed_request.split('.', 2)
        encoded_sig = l[0]
        payload = l[1]
        sig = self.base64_url_decode(encoded_sig)
        data = json.loads(self.base64_url_decode(payload))
        if data.get('algorithm').upper() != 'HMAC-SHA256':
            return None
        else:
            msg = payload
            digestmod = hashlib.sha256
            exp_sig = hmac.new(secret, msg, digestmod).digest()
        if sig != exp_sig:
            return None
        else:
            return data

###facebook retrieve oath token
    def fetch_access_token(self, fb_api_id, fb_api_url, fb_secret, code):
        data = urllib.urlencode({'client_id': fb_api_id,
                                        'redirect_uri': fb_api_url,
                                        'client_secret': fb_secret,
                                        'code': code})
        result = urlfetch.fetch(url=ACCESS_URL,
                                        payload=data,
                                        method=urlfetch.POST,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
        access_token = {}
        split_data = result.content.split('&')
        for parts in split_data:
            part = parts.split('=')
            access_token[part[0]] = part[1]
        token = access_token['access_token']
        return token

###retrieves the facebook user data
    def fetch_facebook_user_data(self, access_tocken):
        data = urllib.urlencode({'access_token': access_tocken})
        result = urlfetch.fetch(url=GRAPH_URL,
                                        payload=data,
                                        method=urlfetch.POST,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
        return result.content
